﻿using iTool.ClusterComponent;
using iTool.Common.Models;
using iTool.PluginCore.Connector;
using iTool.Utils;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace iToolPlugin.WChat
{
    class AccessToken
    {
        public DateTime SetTime { get; set; }
        public string Value { get; set; }
    }

    [Route("{worker}")]
    public class WChatWorker
    {
        private readonly IConfiguration configuration;
        private readonly iToolClusterHostClient iToolClusterClient;
        private string appid => this.configuration.GetSection("WChat").GetValue<string>("Appid");
        private string secret => this.configuration.GetSection("WChat").GetValue<string>("Secret");
        private string tokenUrl { get; }

        private AccessToken accessToken { get; set; }
        HttpClient _httpClient => HttpClientFactory.Create();

        public WChatWorker(iToolClusterHostClient iToolClusterClient, IConfiguration configuration)
        {
            this.configuration = configuration;
            this.iToolClusterClient = iToolClusterClient;
            this.accessToken = new AccessToken();
            this.tokenUrl = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={secret}";
        }

        [Get("MinQrCode/{scene}/{width}/view")]
        public async Task<FileDetails> DownloadWXQRView(string scene, int width, string path, AbstractHttpContext context)
        {
            IKeyValueReader reader = this.iToolClusterClient.GetService<IKeyValueReader>($"{this.appid}_accesstoken");
            this.accessToken = (await reader.GetAsync()).TryToEntity<AccessToken>() ?? new AccessToken();

            if (accessToken.SetTime < DateTime.Now)
            {
                await this.GetAccessToken(reader);
            }

            if (!string.IsNullOrWhiteSpace(accessToken.Value))
            {
                string json = JsonConvert.SerializeObject(new
                {
                    page = path,
                    width = width,
                    scene = scene
                    //check_path = false
                });

                StringContent httpContent = new StringContent(json, Encoding.UTF8, "appliction/json");

                var response = await _httpClient.PostAsync(this.CreateWXAQRCode(accessToken.Value), httpContent);
                var byts = await response.Content.ReadAsByteArrayAsync();

                if (byts.Length > 0)
                {
                    var stream = new MemoryStream(byts);

                    return new FileDetails
                    {
                        ContentType = "image/png",
                        Name = "qr.png",
                        StreamData = stream
                    };

                }
            }

            return null;

        }


        private string CreateWXAQRCode(string access_token)
        {
            return $"https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={access_token}";
        }

        private async Task GetAccessToken(IKeyValueReader reader)
        {
            try
            {
                var responseString = await _httpClient.GetStringAsync(tokenUrl);
                dynamic jsonstr = JsonConvert.DeserializeObject(responseString);

                if (!string.IsNullOrWhiteSpace(jsonstr.access_token.ToString()))
                {
                    accessToken = new AccessToken
                    {
                        Value = jsonstr.access_token.ToString(),
                        SetTime = DateTime.Now.AddSeconds(5000)
                    };

                    await reader.SetAsync(accessToken.TryToJson());
                }
                else
                {
                    accessToken = new AccessToken();
                }
            }
            catch
            {
                accessToken = new AccessToken();
            }
        }

    }

}
